package com.sercomm.ott.mediaplayer;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.sercomm.ott.mediaplayer.viewpager_test.HttpUtil;


import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by davis on 17-11-2.
 */

public class OttHttpTestActivity extends Activity implements View.OnClickListener{

    private static final String TAG = "otttest";
    /*
    public static final String NEXT_PAGE = "http://192.168.1.64:8080/next_page.json";
    public static final String AUTO = "http://192.168.1.64:8080/auto.json";
    public static final String REGISTER = "http://192.168.1.64:8080/register.json";
    public static final String SET_WAN = "http://192.168.1.64:8080/set_wan.json";
    public static final String SET_PASSWORD = "http://192.168.1.64:8080/set_password.json";
    public static final String SET_VOIP = "http://192.168.1.64:8080/set_voip.json";
    */
    private final String MY_TEST = "http://192.168.1.2/RecSms.php";

    private final String NEXT_PAGE = "http://192.168.1.1/cgi-bin/next_page.json";
    private final String AUTO = "http://192.168.1.1/cgi-bin/auto.json";
    private final String REGISTER = "http://192.168.1.1/cgi-bin/register.json";
    private final String SET_WAN = "http://192.168.1.1/cgi-bin/set_wan.json";
    private final String SET_PASSWORD = "http://192.168.1.1/cgi-bin/set_password.json";
    private final String SET_VOIP = "http://192.168.1.1/cgi-bin/set_voip.json";
    Button mButton_request;
    Button mButton_post;
    Button mButton_test;
    Button mButton_mytest;
    TextView responseText;
    TextView postText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ott_httptest_main);
        init();
    }
    private void init(){
        mButton_request = (Button)findViewById(R.id.send_request);
        mButton_post = (Button)findViewById(R.id.post_test);
        mButton_test = (Button)findViewById(R.id.load_test);
        mButton_mytest = (Button)findViewById(R.id.my_test);
        mButton_request.setOnClickListener(this);
        mButton_post.setOnClickListener(this);
        mButton_test.setOnClickListener(this);
        mButton_mytest.setOnClickListener(this);
        responseText = (TextView)findViewById(R.id.response);
        postText = (TextView)findViewById(R.id.post);
    }

    @Override
    public void onClick(View view){
        switch (view.getId()){
            case R.id.send_request:
                //sendRequestWithHttpClient(NEXT_PAGE);
                sendRequestWithHttp(NEXT_PAGE);
                break;
            case R.id.post_test:
                //postWhithHttpClient(SET_PASSWORD);
                postWithHttp(SET_PASSWORD);
                break;
            case R.id.load_test:
                //postWhithHttpClient(SET_VOIP);
                //postWithHttp(SET_VOIP);
                postWithHttp(REGISTER);
                /*
                JSONObject root = new JSONObject();
                try {
                    root.put("sipUsername", "12");
                    root.put("authUsername", "34");
                    root.put("authPassword", "123456");
                }catch (Exception e){
                    e.printStackTrace();
                }
                postWithHttp(SET_VOIP,root);
                */
                break;

            case R.id.my_test:
                postWithHttp(AUTO);
                /*
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        RecSmsToPost("11111");

                    }
                }).start();
                */
                break;

        }
    }

    public static final int SHOW_RESPONSE = 0x000;
    public static final int SHOW_POST = 0x002;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            switch (msg.what){
                case SHOW_RESPONSE:
                    String response = (String)msg.obj;
                    responseText.setText(response);
                    break;
                case SHOW_POST:
                    String result = (String)msg.obj;
                    postText.setText(result);
                    break;
            }
        }
    };
    public void sendRequestWithHttp(final String jsonUrl){
        new Thread(new Runnable() {
            String status = null;
            @Override
            public void run() {
                status = HttpUtil.GetWithHttpClient(jsonUrl);;
                Message message = new Message();
                message.what = SHOW_RESPONSE;
                message.obj = status;
                handler.sendMessage(message);
            }
        }).start();
    }
    public void postWithHttp(final String jsonUrl){
        new Thread(new Runnable() {
            String result = null;
            @Override
            public void run() {
                result = HttpUtil.postWhithHttpClient(jsonUrl);
                Message message = new Message();
                message.what = SHOW_POST;
                message.obj = result;
                handler.sendMessage(message);
                Log.d(TAG,"----result is "+result);
            }
        }).start();
    }
    public void postWithHttp(final String jsonUrl, final JSONObject jsonObject){
        new Thread(new Runnable() {
            String result = null;
            String postResult = null;
            @Override
            public void run() {
                postResult = HttpUtil.postWhithHttpClient(jsonUrl,jsonObject);
                result = HttpUtil.postHttpResult(jsonUrl,postResult);
                Message message = new Message();
                message.what = SHOW_POST;
                message.obj = result;
                handler.sendMessage(message);
                Log.d(TAG,"----result2 is "+result);
            }
        }).start();
    }









    private void postWhithHttpClient(final String jsonUrl){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection=null;
                try {
                    URL url = new URL(jsonUrl);
                    connection = (HttpURLConnection)url.openConnection();
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setRequestMethod("POST");
                    connection.setUseCaches(false);
                    connection.setRequestProperty("Content-Type","application/json");
                    connection.setAllowUserInteraction(true);


                    JSONObject root = new JSONObject();
                    if(jsonUrl.equals(SET_PASSWORD)) {
                        root.put("password", "1111");
                    }else if(jsonUrl.equals(SET_WAN)){
                        root.put("VLAMMode","1");
                        root.put("VLANIDMark","2");
                        root.put("802-1pMark","3");
                        root.put("ServiceMode","4");
                        root.put("Username","5");
                        root.put("Password","6");
                        root.put("AddressingType","7");
                        root.put("ExternalIPAddress","8");
                        root.put("SubnetMark","9");
                        root.put("DefaultGateway","10");
                        root.put("DNSEnabled","11");
                        root.put("DNSServers","12");
                    }else if(jsonUrl.equals(SET_VOIP)){
                        root.put("sipUsername","12");
                        root.put("authUsername","34");
                        root.put("authPassword","123456");
                    }else if(jsonUrl.equals(AUTO)){
                        root.put("type","auto"); //type:auto manual
                    }else if(jsonUrl.equals(REGISTER)){
                        root.put("type","PASSWORD");  //type:OUI_SN  PASSWORD
                    }
                    Log.d(TAG,"----root toString: "+root.toString());
                    OutputStream outputStream = connection.getOutputStream();
                    DataOutputStream out = new DataOutputStream(outputStream);
                    out.writeBytes(root.toString());
                    out.flush();
                    out.close();
                    /*
                    outputStream.write(root.toString().getBytes());
                    outputStream.flush();
                    outputStream.close();*/
                    //服务器返回数据
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            connection.getInputStream()));
                    StringBuffer buffer = new StringBuffer();
                    String str = null;
                    while ((str=reader.readLine()) !=null){
                        buffer.append(str);
                    }
                    Log.d(TAG,"buffer is "+buffer.toString());
                    reader.close();
                }catch (SocketTimeoutException e){
                    Log.d(TAG,"---socket time out");
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(connection!=null){
                        connection.disconnect();
                    }
                }
            }
        }).start();

    }

    private String postWhithHttpClient(String jsonUrl,JSONObject jsonObject){
        HttpURLConnection connection = null;
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(jsonUrl);
            connection = (HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(jsonObject.toString().getBytes());
            outputStream.flush();
            outputStream.close();

            //服务器返回数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));

            String str = null;
            while ((str=reader.readLine()) !=null){
                buffer.append(str);
            }
            reader.close();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(connection!=null){
                connection.disconnect();
            }
            return buffer.toString();
        }
    }

    private String postWhithHttpClient(String jsonUrl,Map<String,String> map){
        HttpURLConnection connection = null;
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(jsonUrl);
            connection = (HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            OutputStream outputStream = connection.getOutputStream();
            byte[] data = getRequestData(map,"utf-8").toString().getBytes();
            outputStream.write(data);
            outputStream.flush();
            outputStream.close();

            //服务器返回数据

            return dealResponseResult(connection.getInputStream());
            /*
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String str = null;
            while ((str=reader.readLine()) !=null){
                buffer.append(str);
            }
            reader.close();
            */
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(connection!=null){
                connection.disconnect();
            }
            return buffer.toString();
        }
    }

    public static String submitPostData(String strUrlPath,Map<String, String> params, String encode) {

        byte[] data = getRequestData(params, encode).toString().getBytes();//获得请求体
        try {

            //String urlPath = "http://192.168.1.9:80/JJKSms/RecSms.php";
            URL url = new URL(strUrlPath);

            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setConnectTimeout(3000);     //设置连接超时时间
            httpURLConnection.setDoInput(true);                  //打开输入流，以便从服务器获取数据
            httpURLConnection.setDoOutput(true);                 //打开输出流，以便向服务器提交数据
            httpURLConnection.setRequestMethod("POST");     //设置以Post方式提交数据
            httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存
            //设置请求体的类型是文本类型
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //设置请求体的长度
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
            //获得输出流，向服务器写入数据
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data);

            int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
            if(response == HttpURLConnection.HTTP_OK) {
                InputStream inptStream = httpURLConnection.getInputStream();
                return dealResponseResult(inptStream);                     //处理服务器的响应结果
            }
        } catch (IOException e) {
            //e.printStackTrace();
            return "err: " + e.getMessage().toString();
        }
        return "-1";
    }
    private void RecSmsToPost(String strRecSmsMsg){
        String strNowDateTime=getNowDateTime("yyyy-MM-dd|HH:mm:ss");//当前时间
        //参数
        Map<String,String> params = new HashMap<String,String>();
        params.put("RECSMSMSG", strRecSmsMsg);
        //params.put("name", "李四");

        //服务器请求路径
        String strUrlPath = MY_TEST;
        String strResult=submitPostData(strUrlPath,params, "utf-8");
        Log.d(TAG,"str Result "+strResult);
        //postText.setText(strResult);

        //openToast("提交完成");
    }
    private String getNowDateTime(String strFormat){
        if(strFormat==""){
            strFormat="yyyy-MM-dd HH:mm:ss";
        }
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat(strFormat);//设置日期格式
        return df.format(now); // new Date()为获取当前系统时间
    }
    public static StringBuffer getRequestData(Map<String, String> params, String encode) {
        StringBuffer stringBuffer = new StringBuffer();        //存储封装好的请求体信息
        try {
            for(Map.Entry<String, String> entry : params.entrySet()) {
                stringBuffer.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), encode))
                        .append("&");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);    //删除最后的一个"&"
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer;
    }

    public static String dealResponseResult(InputStream inputStream) {
        String resultData = null;      //存储处理结果
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        try {
            while((len = inputStream.read(data)) != -1) {
                byteArrayOutputStream.write(data, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        resultData = new String(byteArrayOutputStream.toByteArray());
        return resultData;
    }


    public void sendRequestWithHttpClient(final String jsonUrl){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try{
                    //URL url = new URL("http://10.0.2.2/get_data.json");
                    URL url = new URL(jsonUrl);
                    //URL url = new URL("http://www.baidu.com");
                    connection= (HttpURLConnection)url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    if(connection.getResponseCode() == 200){
                        InputStream in = connection.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine())!=null){
                            response.append(line);
                        }
                        Log.d(TAG,"response is "+response.toString());
                        String status = getStatus(response.toString());
                        Message message = new Message();
                        message.what = SHOW_RESPONSE;
                        message.obj = status;
                        handler.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(connection!=null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
    private String getStatus(String jsonData){
        Log.d(TAG,"-----getStatus "+jsonData);
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonData);
            String status = jsonObject.getString("status");
            return status;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "error";
    }
}
